# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: helpers\application\utils.py
import os.path, logging, ssl, platform
from functools import partial
from settings_provider import settings
from helpers.updater import Updater
from db.data.system_config import get_requests_proxy
from api.descriptors.frontend import data as frontend_api
from helpers.setup_types import *

__logger = logging.getLogger("helpers.application.util")


def adjust_urls():
    if is_setup_type(ON_PREMISE_MASTER):
        frontend_schema = "http"
        if settings.get("server.ssl.certificate"):
            if settings.get("server.ssl.private_key"):
                frontend_schema = "https"
        frontend_host = settings.get("server.host")
        if frontend_host is None:
            frontend_host = settings.get("server.frontend.host")
        frontend_port = settings.get("server.port")
        if frontend_port is None:
            frontend_port = settings.get("server.frontend.port")
        if frontend_port is None:
            frontend_url = "%s://%s" % (frontend_schema, frontend_host)
            settings.set("frontend_url", frontend_url)
        else:
            frontend_url = "%s://%s:%s" % (
                frontend_schema,
                frontend_host,
                frontend_port,
            )
            settings.set("frontend_url", frontend_url)
        base_path = frontend_api["basePath"]
        settings.set("frontend_api_url", frontend_url + base_path)


def adjust_storage_settings():
    base_storage = settings.get("base_storage", None)
    if base_storage:
        if isinstance(base_storage, str):
            if not settings.get("storage.updates"):
                settings.set("storage.updates", os.path.join(base_storage, "updates"))
            if not settings.get("storage.scans"):
                settings.set("storage.scans", os.path.join(base_storage, "scans"))
            if not settings.get("storage.targets"):
                settings.set("storage.targets", os.path.join(base_storage, "targets"))
            if not settings.get("storage.reports"):
                settings.set("storage.reports", os.path.join(base_storage, "reports"))
            if not settings.get("storage.license"):
                settings.set("storage.license", os.path.join(base_storage, "license"))
            if not settings.get("storage.bxss"):
                settings.set("storage.bxss", os.path.join(base_storage, "bxss"))


def git_log():
    try:
        head_file_name = ".git/logs/HEAD"
        if os.path.isfile(head_file_name):
            with open(head_file_name, "rb") as (fh):
                fh.seek(-1024, 2)
                last_line = fh.readlines()[-1].decode().strip()
                __logger.debug("git_log: %s", last_line)
        else:
            __logger.debug("git_log: not found")
    except Exception as e:
        __logger.debug("git_log: %s", e)


def adjust_version_info():
    file_name = "acunetix.version"
    try:
        v = open(file_name, "rt").read().strip()
        __logger.info("found version: %s", v)
        major_version, minor_version, build_number = v.split(".")
        version_info = dict(
            major_version=major_version,
            minor_version=minor_version,
            build_number=build_number,
            str=v,
        )
    except Exception as e:
        __logger.exception("Unable to retrieve version info, exiting [%s]", e)
        import sys
    else:
        settings.set("version_info", version_info)


def adjust_ssl_ca_bundle_path():
    __logger.info("adjusting ca bundle...")
    ssl_ca_bundle_path = settings.get("ssl_ca_bundle_path", None)
    __logger.info("settings ca value: %s", ssl_ca_bundle_path)
    try:
        if ssl_ca_bundle_path == "-":
            settings.set("ssl_ca_bundle_path", False)
        else:
            if ssl_ca_bundle_path is None:
                if platform.system() == "Windows":
                    base_storage = settings.get("base_storage", None)
                    if base_storage:
                        if os.path.isdir(base_storage):
                            ssl_ca_bundle_path = os.path.join(
                                base_storage, "win_ca_certs.pem"
                            )
                            context = ssl.create_default_context()
                            der_certs = context.get_ca_certs(binary_form=True)
                            pem_certs = [
                                ssl.DER_cert_to_PEM_cert(der) for der in der_certs
                            ]
                            with open(ssl_ca_bundle_path, "w") as (outfile):
                                for pem in pem_certs:
                                    outfile.write(pem + "\n")

                            settings.set("ssl_ca_bundle_path", ssl_ca_bundle_path)
                            __logger.info("ca bundle saved to: %s", ssl_ca_bundle_path)
    except Exception as e:
        __logger.exception("adjust_ssl_ca_bundle_path failed with: %s", e)


def create_system_proxy_callback(shard="master"):
    system_proxy_cb = partial(get_requests_proxy, shard)
    settings.set("system_proxy_cb", system_proxy_cb)
    return system_proxy_cb


def create_system_updater():
    version_info = settings.get("version_info")
    storage_updates = settings.get("storage.updates")
    if not storage_updates:
        __logger.error("create_system_updater: storage_updates was not set")
    system_updater = Updater(
        version_info,
        storage_updates,
        os.getcwd(),
        check_interval=43200,
        proxies_cb=settings.get("system_proxy_cb", None),
        ssl_ca_bundle_path=settings.get("ssl_ca_bundle_path", True),
    )
    settings.set("system_update_object", system_updater)
    return system_updater
